package com.paper.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.achievement.dao.CourseRepository;
import com.achievement.dao.SubjectRepository;
import com.achievement.entity.Course;
import com.achievement.entity.Subject;
import com.common.util.TablePage;
import com.exam.dao.ExamRepository;
import com.exam.entity.Exam;
import com.paper.dao.PaperRepository;
import com.paper.entity.Paper;
import com.paper.entity.Topics;
import com.paper.entity.dto.PaperTableDTO;
import com.question.dao.BlankRepository;
import com.question.dao.ExplanationRepository;
import com.question.dao.JudgmentRepository;
import com.question.dao.MultipleRepository;
import com.question.dao.OptionsRepository;
import com.question.dao.SingleRepository;
import com.question.entity.Judgment;
import com.question.entity.Multiple;
import com.question.entity.Options;
import com.question.entity.Single;
import com.user.dao.TeacherRepository;
import com.user.entity.dto.TeacherDTO;

@Service
@Transactional
public class PaperService implements IPaperService {
	@Autowired
	private PaperRepository paperDao;
	@Autowired
	private SubjectRepository subjectDao;
	@Autowired
	private TeacherRepository teacherDao;
	@Autowired
	private OptionsRepository optionsDao;
	@Autowired
	private ExamRepository examDao;
	@Autowired
	private CourseRepository courseDao;
	@Autowired
	private SingleRepository singleDao;
	@Autowired
	private MultipleRepository multipleDao;
	@Autowired
	private BlankRepository blankDao;
	@Autowired
	private JudgmentRepository judgmentDao;
	@Autowired
	private ExplanationRepository explDao;

	public TablePage<PaperTableDTO> findPage(Specification<Paper> spec, Pageable pageable) {
		Page<Paper> page = paperDao.findAll(spec, pageable);
		List<PaperTableDTO> list = new ArrayList<PaperTableDTO>();
		for(Paper p:page.getContent()) {
			
			String subject = null;
			String teacher = null;
			if(p.getSubject()!=null)subject = p.getSubject().getName();
			if(p.getTeacher()!=null)teacher = p.getTeacher().getName();
			
			list.add(new PaperTableDTO(p, subject, teacher));
		}
		return TablePage.getTablePage(new PageImpl<>(list, pageable, page.getTotalElements()));
	}

	public void delete(Long id) {
		//删除试卷，先移除综合题
		Paper paper = paperDao.findOne(id);
		Map<Integer,Topics> list = paper.getTopics();
		List<Integer> _index = new ArrayList<Integer>();
		for(int i=0;i<list.size();i++) {
			if(list.get(i+1).isCompreh()) {
				_index.add(i+1);
			}
		}
		for(int i:_index) {
			paper.getTopics().remove(i);
		}
		paperDao.save(paper);
		paperDao.delete(id);
	}

	public void save(Paper paper,HttpSession session) {
		TeacherDTO t = (TeacherDTO) session.getAttribute("teacher");
		if(t!=null) {
			paper.setTeacher(teacherDao.findOne(t.getId()));
		}else {
			paper.setTeacher(null);
		}
		/*//新建试卷
		
		
		
		Subject subject = null;
		
		if(paper.getSubject()!=null&&paper.getSubject().getId()!=null) {
			subject = subjectDao.findOne(paper.getSubject().getId());
		}
		*/
		for(Integer i:paper.getTopics().keySet()) {
			for(Integer j:paper.getTopics().get(i).getSubtopics().keySet()) {
				if(null!=paper.getTopics().get(i).getSubtopics().get(j).getSingle()) {
					//单选题
					Single single = paper.getTopics().get(i).getSubtopics().get(j).getSingle();
					//single.setSubject(subject);
					String answerNum = single.getAnswer().getNum();
					for(String s:single.getOptions().keySet()) {
						if(single.getOptions().get(s).getNum().equals(answerNum)) {
							System.out.println("单选题选项的num"+single.getOptions().get(s).getId());
							System.out.println("单选题答案的ID"+answerNum);
							paper.getTopics().get(i).getSubtopics().get(j).getSingle().setAnswer(paper.getTopics().get(i).getSubtopics().get(j).getSingle().getOptions().get(s));
						}
					}
					singleDao.save(single);
					
				}else if(null!=paper.getTopics().get(i).getSubtopics().get(j).getMultiple()) {
					//多选题
					Multiple multiple = paper.getTopics().get(i).getSubtopics().get(j).getMultiple();
					//multiple.setSubject(subject);
					
					Set<Options> answers = new HashSet<Options>();
					
					for(String s:multiple.getOptions().keySet()) {
						Options option = new Options();
						String optionNum = multiple.getOptions().get(s).getNum();
						for(Options o:multiple.getAnswers()) {
							if(optionNum.equals(o.getNum())) {
								option.setId(o.getId());
								option.setContent(o.getContent());
								option.setNum(o.getNum());
								optionsDao.save(option);
								
								Options newOption = optionsDao.findByCode(o.getNum());
								
								multiple.getOptions().put(s, newOption);
								
								answers.add(newOption);
							}
						}
					}
					
					multiple.setAnswers(answers);
					multipleDao.save(multiple);
					
				}else if(null!=paper.getTopics().get(i).getSubtopics().get(j).getJudgment()) {
					//判断题
					Judgment judgment = paper.getTopics().get(i).getSubtopics().get(j).getJudgment();
					//judgment.setSubject(subject);
					
					Set<Options> newOptions = new HashSet<Options>();
					
					
					for(Options o:judgment.getOptions()) {
						Options option = new Options();
						option.setId(o.getId());
						option.setContent(o.getContent());
						option.setNum(o.getNum());
						newOptions.add(option);
						if(o.getNum().equals(judgment.getAnswer().getNum())) {
							judgment.setAnswer(option);
						}
					}
					
					judgment.setOptions(newOptions);
					judgmentDao.save(judgment);
					
				}else if(null!=paper.getTopics().get(i).getSubtopics().get(j).getBlank()) {
					//填空题
					//paper.getTopics().get(i).getSubtopics().get(j).getBlank().setSubject(subject);
					blankDao.save(paper.getTopics().get(i).getSubtopics().get(j).getBlank());
				}else if(null!=paper.getTopics().get(i).getSubtopics().get(j).getExplanation()) {
					//解答题
					//paper.getTopics().get(i).getSubtopics().get(j).getExplanation().setSubject(subject);
					explDao.save(paper.getTopics().get(i).getSubtopics().get(j).getExplanation());
				}
			}
		}
		
		//paper.setSubject(subject);
		
		paperDao.save(paper);
	}

	@Override
	public List<Paper> findAll() {
		// TODO Auto-generated method stub
		return (List<Paper>) paperDao.findAll();
	}

	@Override
	public Paper findOne(Long id) {
		// TODO Auto-generated method stub
		return paperDao.findOne(id);
	}

	@Override
	public boolean isUsing(Long id) {
		// TODO Auto-generated method stub
		if(examDao.findByPaperId(id).size()>0)
			return true;
		return false;
	}

	@Override
	public boolean isUsingAndExaming(Long id) {
		// TODO Auto-generated method stub
		List<Exam> list = examDao.findByPaperId(id);
		for(Exam e:list) {
			Date now = new Date();
			if(e.getDate().getTime()<now.getTime()) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List<Paper> findListBycourse(Long id) {
		// TODO Auto-generated method stub
		if(id==null)return null;
		Course course = courseDao.findOne(id);
		System.out.println(course.getName());
		Subject subject = course.getSubject();
		System.out.println(subject.getName());
		return paperDao.findBySubjectId(subject.getId());
	}

}
